//
//  ChosseCityViewController.m
//  MagictoLane
//
//  Created by 锋 on 2017/12/7.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "ChosseCityViewController.h"
#import "CityCountModel.h"
#import "CityNameModel.h"
#import "HotCityModel.h"
#import "CustomSearchBar.h"

@interface ChosseCityViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic, strong) NSMutableArray *filterArray;
@property (nonatomic, strong) CustomSearchBar *searchBar;
@property (nonatomic, strong) NSMutableArray *hotCity;
@property (nonatomic, strong) NSMutableArray *cityCountArr;
@property (nonatomic, strong) NSMutableArray *cityNameArr;
@property (nonatomic, strong) NSMutableArray *indexArr;
@property (nonatomic, strong) NSMutableArray *sectionTitlesArr;
@property (strong, nonatomic) UIView *indexView;
@property(nonatomic, assign) BOOL isChangeSearchBarFrame;//是否要改变searchBar的frame
@end

@implementation ChosseCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _indexArr = [NSMutableArray array];
    _sectionTitlesArr = [NSMutableArray array];
    _filterArray = [NSMutableArray array];
    [self creatUI];
    [self requestHotCity];
    [self requestCity];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillDisappear:(BOOL)animated {
    [_searchBar resignFirstResponder];
}

// MARK:初始化方法
- (void)setupCityTableView {
    CGFloat width = 25;
    //添加indexView
    _indexView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - width, 120, width, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX - 120)];
    _indexView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_indexView];
    
    // 添加索引button
    for (int i = 0; i < self.indexArr.count; i++) {
        UIButton *indexButton = [[UIButton alloc] initWithFrame:CGRectMake(0, i * 15, width, 15)];
        indexButton.backgroundColor = [UIColor whiteColor];
        [indexButton setTitle:self.indexArr[i] forState:UIControlStateNormal];
        [indexButton setTitleColor:RGB(128, 128, 128) forState:UIControlStateNormal];
        indexButton.titleLabel.font = [UIFont systemFontOfSize:10];
        indexButton.tag = i;
        [indexButton addTarget:self action:@selector(jumpToSection:) forControlEvents:UIControlEventTouchUpInside];
        [_indexView addSubview:indexButton];
    }
    
    _cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 120, SCREEN_WIDTH - width, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX - 120) style:UITableViewStylePlain];
    _cityTableView.delegate = self;
    _cityTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _cityTableView.tableHeaderView = view;
    _cityTableView.tableFooterView = view;
    _cityTableView.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
        _cityTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _cityTableView.estimatedRowHeight = 0;
    _cityTableView.estimatedSectionHeaderHeight = 0;
    _cityTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_cityTableView];
}

- (void)creatUI
{
    [_currentCityBtn setTitle:_currentCityName forState:UIControlStateNormal];
    [self addSearchBar];
//    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 6.5, 120, 31)];
//    _searchBar.backgroundColor = [UIColor clearColor];
//    _searchBar.delegate = self;
//    self.navigationItem.titleView = _searchBar;
    UIBarButtonItem *rightBut = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo"] style:UIBarButtonItemStylePlain target:self action:@selector(searchCity)];
    self.navigationItem.rightBarButtonItem = rightBut;
    UITapGestureRecognizer *hideKeyBoard = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoardAction)];
    hideKeyBoard.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:hideKeyBoard];
}

// MARK:自定义searchbar
- (void)addSearchBar {
    
    _searchBar = [self addSearchBarWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 2 * 44 - 2 * 15, 44)];
    UIView *wrapView = [[UIView alloc] initWithFrame:_searchBar.frame];
    [wrapView addSubview:_searchBar];
    self.navigationItem.titleView = wrapView;
}
- (CustomSearchBar *)addSearchBarWithFrame:(CGRect)frame {
    
    self.definesPresentationContext = YES;
    
    CustomSearchBar *searchBar = [[CustomSearchBar alloc]initWithFrame:frame];
    searchBar.delegate = self;
    [searchBar setShowsCancelButton:NO];
//    [searchBar setTintColor:[UIColor lightGrayColor]];   //设置光标颜色
    
    if (self.isChangeSearchBarFrame) {
        
        CGFloat height = searchBar.bounds.size.height;
        CGFloat top = (height - 20.0) / 2.0;
        CGFloat bottom = top;
        
        searchBar.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    }
    return searchBar;
}

// MARK:数据请求方法
- (void)requestCity {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
    [HYBaseHandler requestCityParmers:nil Success:^(id obj) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        if ([obj server_Getcodecheck])
        {
            _cityCountArr = [CityCountModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            for (int i = 0; i < _cityCountArr.count; i++) {
                CityCountModel *model = _cityCountArr[i];
                _cityNameArr = [CityNameModel mj_objectArrayWithKeyValuesArray:model.cities];
            }
            for (int i = 0; i < _cityCountArr.count; i++) {
                CityCountModel *model = _cityCountArr[i];
                NSString *indexStr = model.letter;
                [_indexArr addObject:indexStr];
                [_sectionTitlesArr addObject:indexStr];
            }
            
            [_indexArr insertObject:@"历史" atIndex:0];
            [_indexArr insertObject:@"热门" atIndex:1];
            [self setupCityTableView];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
    }];
}

- (void)requestHotCity {
    WEAKSELF;
    [HYBaseHandler requestHotCityParmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            NSLog(@"%@", obj[@"data"]);
            _hotCity = [HotCityModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            HotCityModel *firstModel = _hotCity[0];
            [_firstHotCityBtn setTitle:firstModel.name forState:UIControlStateNormal];
            HotCityModel *secondModel = _hotCity[1];
            [_secondHotCityBtn setTitle:secondModel.name forState:UIControlStateNormal];
            HotCityModel *thirdModel = _hotCity[2];
            [_thirdHotCityBtn setTitle:thirdModel.name forState:UIControlStateNormal];
            HotCityModel *fourthModel = _hotCity[3];
            [_fourthHotCityBtn setTitle:fourthModel.name forState:UIControlStateNormal];
            HotCityModel *fifthModel = _hotCity[4];
            [_fifthHotCityBtn setTitle:fifthModel.name forState:UIControlStateNormal];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
    }];
}


// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_filterArray && _filterArray.count > 0) {
        return 1;
    } else {
        return _cityCountArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_filterArray && _filterArray.count > 0) {
        return _filterArray.count;
    } else {
        CityCountModel *model = _cityCountArr[section];
        return model.cities.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    view.backgroundColor = RGB(249, 250, 249);
    UILabel *sectionTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, SCREEN_WIDTH - 20, 20)];
    sectionTitleLabel.text = self.sectionTitlesArr[section];
    [view addSubview:sectionTitleLabel];
    
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    if (_filterArray && _filterArray.count > 0) {
        CityNameModel *nameModel = _filterArray[indexPath.row];
        cell.textLabel.text = nameModel.name;
    } else {
        CityCountModel *countModel = _cityCountArr[indexPath.section];
        CityNameModel *nameModel = countModel.cities[indexPath.row];
        cell.textLabel.text = nameModel.name;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CityNameModel *nameModel;
    if (_filterArray && _filterArray.count > 0) {
        nameModel = _filterArray[indexPath.row];
    } else {
        CityCountModel *countModel = _cityCountArr[indexPath.section];
        nameModel = countModel.cities[indexPath.row];
    }
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [nameModel.lat doubleValue];
    coordinate.longitude = [nameModel.lng doubleValue];
    self.cityBlockWithName(nameModel.name, coordinate);
    [LTools cache:nameModel.ID ForKey:SERVER_CityID];
    [_searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

// MARK:点击方法
- (void)searchCity {
    [_searchBar becomeFirstResponder];
}

- (void)jumpToSection:(UIButton *)sender {
    if (_filterArray.count == 0) {
        if (sender.tag == 0) {
            
        } else if (sender.tag == 1) {
            
        } else {
            [_cityTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sender.tag - 2] atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }
}
- (IBAction)onClickCurrentCityBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickFirstHotCityBtn:(id)sender {
    HotCityModel *model = _hotCity[0];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [model.lat doubleValue];
    coordinate.longitude = [model.lng doubleValue];
    self.cityBlockWithName(model.name,coordinate);
    [LTools cache:model.cityId ForKey:SERVER_CityID];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickSecondHotCityBtn:(id)sender {
    HotCityModel *model = _hotCity[1];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [model.lat doubleValue];
    coordinate.longitude = [model.lng doubleValue];
    self.cityBlockWithName(model.name,coordinate);
    [LTools cache:model.cityId ForKey:SERVER_CityID];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickFThirdHotCityBtn:(id)sender {
    HotCityModel *model = _hotCity[2];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [model.lat doubleValue];
    coordinate.longitude = [model.lng doubleValue];
    self.cityBlockWithName(model.name,coordinate);
    [LTools cache:model.cityId ForKey:SERVER_CityID];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickFourthHotCityBtn:(id)sender {
    HotCityModel *model = _hotCity[3];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [model.lat doubleValue];
    coordinate.longitude = [model.lng doubleValue];
    self.cityBlockWithName(model.name,coordinate);
    [LTools cache:model.cityId ForKey:SERVER_CityID];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickFifthHotCityBtn:(id)sender {
    HotCityModel *model = _hotCity[4];
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = [model.lat doubleValue];
    coordinate.longitude = [model.lng doubleValue];
    self.cityBlockWithName(model.name,coordinate);
    [LTools cache:model.cityId ForKey:SERVER_CityID];
    [self.navigationController popViewControllerAnimated:YES];
}

//MARK: 搜索方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self.filterArray removeAllObjects];   //过去数据全部消除
    
    for (int i = 0; i < self.cityCountArr.count; i++) {
        CityCountModel *countModel = _cityCountArr[i];
        NSArray *arr = countModel.cities;
        for (int j = 0; j < arr.count; j++) {
            CityNameModel *nameModel = arr[j];
            if ([nameModel.name containsString:self.searchBar.text]) {
                [self.filterArray addObject:nameModel];
            }
        }
    }
    
    [self.cityTableView reloadData];
//    [self.areaListTableView reloadData];    //重置TableView
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /* 防止错乱停止编辑*/
    [self.searchBar resignFirstResponder];
}

- (void)hideKeyBoardAction {
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
